<template>
    <div class="page-home">
        <header class="header">
            <div class="location" @click="checkLocation" style="">
                <div class="icon-wrapper" style="margin-right: 7px">
                    <el-icon><Location /></el-icon>
                </div>
                <span v-if="getLocation" style="font-size: 30px;">{{ locationName }}</span>
                <span v-if="getLocation" style="font-size: 10px;bottom:0px; margin-left: 10px">定位不准？点击重试</span>
                <span v-if="!getLocation">点此获取定位</span>
                <router-link to="welcome">
                    <div class="edit-icon-wrapper">
                        <el-icon><UserFilled style="color: white; height: 28px; width: 28px" /></el-icon>
                    </div>
                </router-link>

            </div>
            <!-- 搜索 -->
            <div class="search-word" >
                <input type="text" v-model="content" class="search-input" placeholder="搜索商家、商品"/>
                <button @click="search">搜索</button>
            </div>
        </header>

        <!-- 首页 slider 导航 -->
        <!--        <div class="block text-center" m="t-4">-->
        <!--            <el-carousel trigger="click" height="250px" :autoplay="false">-->
        <!--                <el-carousel-item v-for="item in 2" :key="item">-->
        <!--                    <div class="index-slider">-->
        <!--                        <Swipe :auto="0"> &lt;!&ndash; swipe 设置不自动滚动 &ndash;&gt;-->
        <!--                            <Swipe-item>-->

        <!--                            </Swipe-item>-->
        <!--                        </Swipe>-->
        <!--                    </div>-->
        <!--                </el-carousel-item>-->
        <!--            </el-carousel>-->
        <!--        </div>-->
        <div class="index-slider">
            <Swipe :auto="0"> <!-- swipe 设置不自动滚动 -->
                <Swipe-item>
                    <router-link to="/searchSweet">
                        <div class="slide-item">
                            <img src="../views/slider-pic/slider-pic10.jpeg" alt="甜品">
                            <span class="title">甜品</span>
                        </div>
                    </router-link>
                    <router-link to="/searchDrink">
                        <div class="slide-item">
                            <img src="../views/slider-pic/slider-pic2.jpeg" alt="饮品">
                            <span class="title">饮品</span>
                        </div>
                    </router-link>
                    <router-link to="/searchSnack">
                        <div class="slide-item">
                            <img src="../views/slider-pic/slider-pic13.jpeg" alt="小吃">
                            <span class="title">小吃</span>
                        </div>
                    </router-link>
                    <router-link to="/searchBreakfast">
                        <div class="slide-item">
                            <img src="../views/slider-pic/slider-pic4.jpeg" alt="早餐">
                            <span class="title">早餐</span>
                        </div>
                    </router-link>
                    <router-link to="/searchFruit">
                        <div class="slide-item">
                            <img src="../views/slider-pic/slider-pic5.jpeg" alt="果蔬生鲜">
                            <span class="title">果蔬生鲜</span>
                        </div>
                    </router-link>
                    <router-link to="/searchMeat">
                        <div class="slide-item">
                            <img src="../views/slider-pic/slider-pic9.jpeg" alt="卤味">
                            <span class="title">卤味</span>
                        </div>
                    </router-link>
                    <router-link to="/searchFastFood">
                        <div class="slide-item">
                            <img src="../views/slider-pic/slider-pic11.jpeg" alt="快餐">
                            <span class="title">快餐</span>
                        </div>
                    </router-link>
                    <router-link to="/searchHomecook">
                        <div class="slide-item">
                            <img src="../views/slider-pic/slider-pic8.jpeg" alt="家常菜">
                            <span class="title">家常菜</span>
                        </div>
                    </router-link>
                </Swipe-item>
            </Swipe>
        </div>
        <div class="index-seller">
            <div class="title" style="height:30px"><p>推荐商家</p></div>
            <el-row :gutter="20" v-for="item in shopList" @click="toMerchant(item.arrayId)" class="shop-item">
                <el-col :span="3" ><img :src="item.image" class="image"/></el-col>
                <el-col :span="10">
                    <div class="main">
                        <section class="line-wrapper">
                            <h3 class="shopname" style="font-size: 25px;">
                                <span>{{item.shopName}}</span>
                            </h3>
                        </section>

                        <section class="line-wrapper">
                            <div class="moneylimit">
                                <div>
                                    <span>月售{{item.monthlyNum}}单</span>
                                </div>
                                <span class="split">￥{{item.dropOffFee}}起送 </span>
                            </div>
                        </section>
                    </div>
                </el-col>
                <el-col :span="6">
                    <div class="timedistanceWrap">
                        <span class="split">{{item.distance}}公里</span>
                        <span>￥{{item.personAmount}}/人</span><br>
                        <span>电话:{{item.shopTelephone}}</span>
                    </div>
                </el-col>
            </el-row>
        </div>
    </div>
</template>

<script setup>
    import {computed, onMounted, onBeforeMount, ref, shallowRef} from 'vue'
    import {allShop} from "../api/shop";

    import { useStore } from "vuex";
    import {useRouter} from 'vue-router'
    import state from "../store";
    import store from "../store";
    import {
        Location, User, UserFilled
    } from '@element-plus/icons-vue'
    import AMapLoader from "@amap/amap-jsapi-loader";
    import {$get} from "../utils/addressRequest";
    import Decimal from "decimal.js";
    import {getMonthlyNum, getPersonAmount} from "../api/order";


    const content=ref("")
    const router=useRouter();
    const search=()=>{

        router.push({name:'searchresult',params:{content:content.value}})
    }
    const shopList=ref([])
    const locationName=ref('')
    let myAMap;
    const getLocation=ref(false)
    let lng=ref(0)
    let lat=ref(0)
    const typeList=ref([])
    onMounted( async ()=>{
        const res =await AMapLoader.load({
            key: "0660b1d1e3b8275101d54732f4607219",             // 申请好的Web端开发者Key，首次调用 load 时必填
            version: "2.0",      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
            plugins: ['AMap.Geolocation','AMap.Geocoder'],       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        })
        myAMap=res;
        await checkLocation()
        //获取商家
        let res1 = await allShop()
        //计算距离
        await computedDistance(res1);
        setTimeout(() => {
            computedFeeAndNum();
        }, 500);
    })

    //计算距离
    const computedDistance=(res)=>{
        shopList.value=res.data
        for(let i=0;i<res.data.length;i++){
            shopList.value[i].arrayId=i;
            let addressShop=shopList.value[i].provinceName
                +shopList.value[i].cityName
                +shopList.value[i].districtName
                +shopList.value[i].detail
            computedLocation(addressShop,i)
        }
    }
    //计算人均和月总订单销量
    const computedFeeAndNum=()=>{
        for(let i=0;i<shopList.value.length;i++){
            getPersonAmount({id:shopList.value[i].id}).then(res=>{
                shopList.value[i].personAmount=res.data;
            })
            getMonthlyNum({id:shopList.value[i].id}).then(res=>{
                shopList.value[i].monthlyNum=res.data;
            })
        }

    }
    //decimal：两数相加
    const add=(x,y)=>{
        if(!x){
            x=0
        }
        if(!y){
            y=0
        }
        const xx=new Decimal(x)
        const yy=new Decimal(y)
        return xx.plus(yy).toNumber()
    }
    //decimal：两数相乘
    const mul=(x,y)=>{
        if(!x){
            x=0
        }
        if(!y){
            y=0
        }
        const xx=new Decimal(x)
        const yy=new Decimal(y)
        return xx.mul(yy).toNumber()
    }

    //计算经纬度信息
    const computedLocation= async (Address,i)=>{
        let {geocodes} = await $get('https://restapi.amap.com/v3/geocode/geo?parameters',{
            //Web端的key
            key:'2b71974950a51f8c24eb45a1e462a84e',
            //地址
            address:Address
        })
        //坐标地址
        let location1=geocodes[0].location
        const location11 = location1.split(",").map(parseFloat);
        let p1= new myAMap.LngLat(location11[0],location11[1])
        let p2= new myAMap.LngLat(lng.value,lat.value)
        let dis = myAMap.GeometryUtil.distance(p1,p2);
        shopList.value[i].distance = (dis / 1000).toFixed(2);
    }

    //跳转到merchantHome
    const toMerchant=(id)=>{
        //保存商家id
        state.commit("saveMerchantId",shopList.value[id].id)
        //保存商家地址
        state.commit("saveAddress",shopList.value[id].provinceName
            +shopList.value[id].cityName
            +shopList.value[id].districtName
            +shopList.value[id].detail
        )
        router.push({path:'/merchanthome'})
    }
    //定位
    const checkLocation=async ()=>{
        getLocation.value=true
        //使用插件
        myAMap.plugin('AMap.Geolocation', function() {
            let geolocation = new myAMap.Geolocation({
                enableHighAccuracy: true, // 是否使用高精度定位，默认：true
                timeout: 10000, // 设置定位超时时间，默认：无穷大
                // 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
                buttonOffset: new AMap.Pixel(10, 20),
                //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                zoomToAccuracy: true,
                //  定位按钮的排放位置,  RB表示右下
                buttonPosition: 'RB'
            })
            //获取定位经纬度坐标
            geolocation.getCurrentPosition(function(status,result){
                if(status==='complete'){
                    let location1=[]
                    // 定位的经纬度
                    location1[0]=result.position.lng
                    location1[1]=result.position.lat
                    lng.value=location1[0]
                    lat.value=location1[1]
                    state.commit("saveLocation",location1)
                    console.log(location1)
                }else{
                    //document.getElementById('tip').innerHTML = '定位失败';
                }
            });
            //获取当前城市名称
            geolocation.getCityInfo(function(status,result){
                console.log(status)
                if(status==='complete'){
                    locationName.value=result.city
                    state.commit("saveLocationName",locationName.value)
                }else{
                    //console.log(result)
                    // document.getElementById('tip').innerHTML = '定位失败';
                    locationName.value="天津市"
                    state.commit("saveLocationName",locationName.value)
                }
            });
        })
        let {geocodes} = await $get('https://restapi.amap.com/v3/geocode/geo?parameters',{
            //Web端的key
            key:'2b71974950a51f8c24eb45a1e462a84e',
            //地址
            address:'泰达外包产业园'
        })
        let location1=geocodes[0].location
        const location11 = location1.split(",").map(parseFloat);
        let location2=[]
        lng.value=location11[0]
        lat.value=location11[1]
        location2[0]=location11[0]
        location2[1]=location11[1]
        state.commit("saveLocation",location2)
    }

    //获取定位信息
    const locations = computed(() => {
        return store.getters.getLocation
    })


</script>
<style lang="less" src="./home.less" scoped></style>
<!-- swipe的css + 改写 -->
<style>
    .mint-swipe,.mint-swipe-items-wrap{overflow:hidden;position:relative;height:100%}.mint-swipe-items-wrap{-webkit-transform:translateZ(0);transform:translateZ(0)}.mint-swipe-items-wrap>div{position:absolute;-webkit-transform:translateX(-100%);transform:translateX(-100%);width:100%;height:100%;display:none}.mint-swipe-items-wrap>div.is-active{display:block;-webkit-transform:none;transform:none}.mint-swipe-indicators{position:absolute;bottom:10px;left:50%;-webkit-transform:translateX(-50%);transform:translateX(-50%)}.mint-swipe-indicator{width:8px;height:8px;display:inline-block;border-radius:100%;background:#ccc;margin:0 3px}.mint-swipe-indicator.is-active{background: #0096ff;}
    .search-word{
        position: relative;
        width: 100%;
    }
    .search-word input{
        width: 100%;
        height: 2.3rem;
        margin: 0.2rem 0;
        text-align: center;
        border-radius: 0.96rem;
        box-shadow: 0 0.026667rem 0.066667rem 0 rgba(0,0,0,.2);
        font-size: 0.346667rem;
        color: #333;
    }
    .search-word button{
        position: absolute;
        top: 12px;
        right: 7px;
        background-color: #fff;
        border: none;
        outline: none;
    }
    .el-row {
        margin-bottom: 20px;
    }
    .image{
        width: 150px;
        height: 150px;
    }
    .main {
        flex-grow: 1;
        padding: .4rem .266667rem .4rem 0;
    }

    .main .line-wrapper:not(:first-child) {
        margin-top: 0.2rem;
    }

    .main .line-wrapper {
        font-size: .493333rem;
        color: #666;
    }

    .main .line-wrapper .shopname {
        max-width:500px;
        font-weight: 700;
        font-size: 50px;
    }


    .main .line-wrapper .supportWrap .supper i {
        display: inline-block;
        line-height: 1;
        margin-left: .066667rem;
        color: rgb(153, 153, 153);
        border: 0.013333rem solid rgb(221, 221, 221);
        font-size: .266667rem;
    }

    .main .line-wrapper .deliveryWrap span:not(:last-child) {
        margin-right: .08rem;
    }

    .main .line-wrapper .moneylimit {
        margin-top: 60px;
    }


    .timedistanceWrap {
        margin-top:70px;
        font-size: .493333rem;
        color: #999;
    }
    .location {
        display: flex;
        align-items: center;
    }

    .icon-wrapper {
        margin-right: 10px;
    }
    .edit-icon-wrapper {
        position: absolute;
        right: 30px;
        top:20px;
    }
    .shop-item{
        padding: 10px;
        margin-bottom: 10px;
        border-radius: 20px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
        background-color: rgba(176, 224, 230, 0.4);
        border: 1px solid rgba(0, 191, 255, 0.3);
    }


    .location:hover {
        cursor: pointer;
    }

    .shop-item:hover {
        cursor: pointer;
    }

</style>

